package com.ucode.hrm.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ucode.hrm.handle.FddAPIHandler;
import com.ucode.hrm.mapper.HrmCompanyMapper;
import com.ucode.hrm.service.HrmCompanyService;
import com.ucode.model.hrm.HrmCompany;
import com.ucode.model.hrm.enums.HrmThreeSignTypeEnum;
import com.ucode.tool.util.IdentifyUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Service
public class HrmCompanyServiceImpl implements HrmCompanyService {

    @Resource
    private HrmCompanyMapper hrmCompanyMapper;

    @Resource
    private FddAPIHandler fddAPIHandler;

    @Override
    public HrmCompanyMapper initMapper() {
        return hrmCompanyMapper;
    }

    @Override
    public Long insert(HrmCompany hrmCompany) {
        if(ObjUtil.isNull(hrmCompany.getId()))
            hrmCompany.setId(IdentifyUtils.getDefaultSnowflakeId());

        if(StrUtil.isNotBlank(hrmCompany.getStorageUrl())) {
            String signatureId = fddAPIHandler.addSignature(hrmCompany.getStorageUrl());
            //暂时只支持法大大，后期需要适配其他第三方时，再进行扩展
            hrmCompany.setThreeStorageType(HrmThreeSignTypeEnum.FDD.getCode());
            hrmCompany.setThreeStorageId(signatureId);
        }

        int i = hrmCompanyMapper.insert(hrmCompany);
        return i > 0 ? hrmCompany.getId() : null;
    }

    @Override
    public int update(HrmCompany hrmCompany) {
        HrmCompany dbBean = this.validate(hrmCompany.getId());

        //印章变化了
        if(StrUtil.isNotBlank(hrmCompany.getStorageUrl()) && !dbBean.getStorageUrl().equals(hrmCompany.getStorageUrl())) {
            String signatureId = fddAPIHandler.addSignature(hrmCompany.getStorageUrl());
            //暂时只支持法大大，后期需要适配其他第三方时，再进行扩展
            hrmCompany.setThreeStorageType(HrmThreeSignTypeEnum.FDD.getCode());
            hrmCompany.setThreeStorageId(signatureId);
        }

        return hrmCompanyMapper.update(hrmCompany);
    }
}
